package cn.zniot.so.application.data;

import cn.zniot.so.application.SessionManager;
import cn.zniot.so.application.constant.Constants;
import cn.zniot.so.application.service.ControlSyncManager;
import cn.zniot.so.application.util.PropertyUtil;
import cn.zniot.so.transport.asynpack.LogicCotrolPacketD;
import cn.zniot.so.transport.asynpack.Zniot2PacketC;

import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;

import java.util.concurrent.ConcurrentLinkedQueue;

public class Session {

	// TBox入库队列
	public static ConcurrentLinkedQueue<LogicCotrolPacketD> tcpQueue = new ConcurrentLinkedQueue<LogicCotrolPacketD>();

	public static ConcurrentLinkedQueue<LogicCotrolPacketD> m_iosession = new ConcurrentLinkedQueue<LogicCotrolPacketD>();

	private static Logger logger = Logger.getLogger(Session.class);

	private static Zniot2PacketC packet = null;

	public static void sendLeaveMessage(String ipAndPort) {
		if (ipAndPort != null) {
			String imei = PropertyUtil.getInstance().getIMEIByIpPort(ipAndPort);
			if (imei != null) {
				imei = Constants.SLEEP_SEND_COMMAND + imei.substring(1);
				IoSession session = getBoxIoSession(imei);
				if (session != null) {
					if (packet == null) {
						packet = new Zniot2PacketC();
					}
					packet.setCode(Constants.CLIENT_DOWN);
					session.write(((Zniot2PacketC) packet));
				}
			}
		}
	}

	/**
	 * 获取服务器与盒子通信Session
	 */
	public static IoSession getBoxIoSession(String imei) {
		String ipAndPort = ControlSyncManager.getInstance().getIpAndPortByimse(imei);
		if (ipAndPort == null) {
			if (logger.isDebugEnabled()) {
				logger.debug("not find corresponding box ipAndPort");
			}
			return null;
		}
		IoSession boxiosession = SessionManager.getInstance().getSession(ipAndPort);
		if (boxiosession == null) {
			if (logger.isDebugEnabled()) {
				logger.debug("not find IoSession");
			}
			return null;
		}
		return boxiosession;
	}
}
